﻿using Mina.Core.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mina.Core.Session;

namespace SharpIM
{
    /// <summary>
    /// 分发消息
    /// </summary>
    public class MessageHandler : IoHandlerAdapter
    {
        public static HttpServer _httpServer = new HttpServer();
        public static ChatServer _chatServer = new ChatServer();
        public static WebSocketServer _webss = new WebSocketServer();
        public override void MessageReceived(IoSession session, object message)
        {
            var httpRequest = message as HttpRequest;
            if (httpRequest != null)
            {
                var resp = _httpServer.ProcessRequest(httpRequest);
                if (resp == null)
                {
                    resp = httpRequest.CreateEmptyResponse();
                }
                session.Write(resp);
                //session.CloseOnFlush();
            }
            else
            {
                var request = message as BinaryRequest;
                if (request != null)
                {
                    var resp = _chatServer.ProcessRequest(request);
                    session.Write(resp);
                }
                else
                {
                    var wbsockReq = message as WebSocketRequest;
                    if (wbsockReq != null)
                    {
                        var resp = _webss.ProcessRequest(wbsockReq);
                        session.Write(resp);
                    }
                    else
                    {
                        session.CloseNow();
                    }
                }
            }
        }
    }
}
